import tool.TreeNode;

import java.util.HashMap;
import java.util.Map;

/**
 * @Description: 从前序与中序遍历序列构造二叉树
 * @Date:Create in 11:35  2022/8/1
 */
public class buildTree0105 {
    Map<Integer, Integer> map;

    public TreeNode buildTree(int[] preorder, int[] inorder) {
        map = new HashMap<>();
        for (int i = 0; i < inorder.length; i++) {
            map.put(inorder[i], i);
        }
        return findNode(preorder,0,preorder.length,inorder,0,inorder.length);
    }

    public TreeNode findNode(int[] preorder, int preBegin, int preEnd, int[] inorder, int inBegin, int inEnd) {
        if (preBegin >= preEnd || inBegin >= inEnd) {
            return null;
        }
        int rootIndex = map.get(preorder[preBegin]);
        TreeNode root = new TreeNode(inorder[rootIndex]);
        int lenOfleft = rootIndex - inBegin;
        root.left = findNode(preorder,preBegin+1,preBegin+lenOfleft+1,inorder,inBegin,inBegin+lenOfleft);
        root.right = findNode(preorder,preBegin+lenOfleft+1,preEnd,inorder,inBegin+lenOfleft+1,inEnd);
        return root;
    }
}
